package com.yoga.service.impl;

import com.yoga.service.UploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.Set;

/**
 * @author yan
 * @date 2025/8/13
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${upload.location}")
    private String uploadPath;//文件上传路径
    @Override
    public String uploadImage(MultipartFile file, String type) {
        //白名单校验文件扩展名
        if (!isValidImage(file.getOriginalFilename())){
            throw new RuntimeException("文件格式错误");
        }
        //限制文件大小
        if (file.getSize() > 1024 * 1024 * 5){
            throw new RuntimeException("文件大小不可超过5MB");
        }
        //创建目录
        File dir = new File(uploadPath + "/images/"+ type);
        if (!dir.exists()){
            boolean b = dir.mkdirs();
            if (!b){
                throw new RuntimeException("创建目录失败");
            }
        }
        //给上传的文件起名
        LocalDateTime now = LocalDateTime.now();
        String fileName = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        Random random = new Random();
        int sid = random.nextInt(10000);
        fileName=fileName+"-"+sid;

        //拼扩展名
        String extension = getFileExt(file.getOriginalFilename());
        fileName = fileName + extension;
        String fullName = dir.getAbsolutePath() + "/" + fileName;
        //保存文件
        File target = new File(fullName);

        //存储文件
        try {
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("保存图片失败");
        }

        //返回图片路径

        return "/images/" + type + "/" + fileName;
    }
    //白名单校验法
    private boolean isValidImage(String fileName){
        Set<String> allowedExt = Set.of(".jpg", ".png", ".jpeg", ".gif");
        if(fileName==null||fileName.lastIndexOf(".")==-1){
            return false;
        }
        String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        return allowedExt.contains(ext);
    }
    //获取文件扩展名
    private String getFileExt(String fileName){
        if(fileName==null||fileName.lastIndexOf(".")==-1){
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
